চাইল্ড প্রসেস মডিউল কি?
চাইল্ড প্রসেস মডিউল হল একটি বিল্ট-ইন Node.js মডিউল যা আপনাকে চাইল্ড প্রসেস তৈরি ও পরিচালনা করতে দেয়।
এটি বহিরাগত কমান্ডগুলি চালানো এবং সাবপ্রসেস ইভেন্টগুলির সাথে ইন্টারঅ্যাক্ট করার একাধিক উপায় সরবরাহ করে।
এই দক্ষতা নিম্নলিখিত কাজের জন্য অপরিহার্য:
এক্সিকিউটিং সিস্টেম কমান্ড
আপনার Node.js অ্যাপ্লিকেশন থেকে সিস্টেম কমান্ড চালান
CPU-নিবিড় কাজ চলমান
পৃথক প্রক্রিয়ায় CPU- নিবিড় কাজ চালান
সমান্তরাল প্রক্রিয়া
একাধিক CPU কোর ব্যবহার করতে সমান্তরালভাবে একাধিক প্রক্রিয়া চালান
বাহ্যিক প্রোগ্রামগুলির সাথে ইন্টারফেস
বাহ্যিক প্রোগ্রাম এবং স্ক্রিপ্টের সাথে ইন্টারফেস
চাইল্ড প্রসেস মডিউল আমদানি করা হচ্ছে
চাইল্ড প্রসেস মডিউলটি ডিফল্টরূপে Node.js-এ অন্তর্ভুক্ত থাকে।
আপনি প্রয়োজন করে আপনার স্ক্রিপ্টে এটি ব্যবহার করতে পারেন:
const childProcess = require('child_process');
// Or using destructuring to access specific methods
const { exec, spawn, fork } = require('child_process');
পদ্ধতি যা শিশু প্রক্রিয়া তৈরি করে
চাইল্ড প্রসেস মডিউল শিশু প্রক্রিয়া তৈরি ও পরিচালনার জন্য চারটি প্রাথমিক পদ্ধতি প্রদান করে, প্রতিটিতে বিভিন্ন আচরণ এবং ব্যবহারের ক্ষেত্রে রয়েছে:
| পদ্ধতি | ব্যাখ্যা | কেস ব্যবহার করুন |
|---|---|---|
| exec() | একটি শেল তৈরি করে এবং আউটপুট বাফার করে একটি কমান্ড চালায় | আপনি যখন একটি শেল কমান্ড চালাতে চান এবং পুরো আউটপুটটি একবারে পেতে চান |
| execFile() | exec() এর মতো কিন্তু একটি শেল তৈরি করে না | ব্যাখ্যা ছাড়াই ফাইল-ভিত্তিক কমান্ড চালানোর ক্ষেত্রে শেলটি খুব দক্ষ |
| spawn() | শেলটি স্পনিং ছাড়াই একটি নতুন প্রক্রিয়ার জন্ম দেয়, I/O স্ট্রিমিং সহ | দীর্ঘ-চলমান প্রক্রিয়া বা বড় আউটপুট নিয়ে কাজ করার সময় |
| fork() | Node.js spawn() | আপনি যখন IPC এর সাথে একটি পৃথক প্রক্রিয়া হিসাবে অন্য Node.js মডিউল চালাতে চান |
exec() পদ্ধতি
exec() পদ্ধতি একটি শেল তৈরি করে এবং সেই শেলের মধ্যে একটি কমান্ড কার্যকর করে।
এটি সম্পূর্ণ আউটপুট বাফার করে এবং কমান্ডটি সম্পূর্ণ হলে একটি কলব্যাক সহ এটি ফেরত দেয়।
const { exec } = require('child_process');
// Execute the 'ls -la' command (or 'dir' on Windows)
const command = process.platform === 'win32' ? 'dir' : 'ls -la';
exec(command, (error, stdout, stderr) => {
if (error) {
console.error(`Error executing command: ${error.message}`);
return;
}
if (stderr) {
console.error(`Command stderr: ${stderr}`);
}
console.log(`Command output:\n${stdout}`);
});
// With options
exec('echo $HOME', {
env: { HOME: '/custom/home/directory' }
}, (error, stdout, stderr) => {
console.log(`Custom home directory: ${stdout.trim()}`);
});
সতর্কতা:
exec() এ কখনই অস্বাস্থ্যকর ব্যবহারকারীর ইনপুট প্রেরণ করবেন না কারণ এটি সম্পূর্ণ শেল সিনট্যাক্স সহ কমান্ডগুলি চালায়, যা কমান্ড ইনজেকশন আক্রমণের দিকে নিয়ে যেতে পারে।
exec() প্রতিশ্রুতি দিয়ে
কলব্যাক পরিচালনা করতে একটি প্রতিশ্রুতি মোড়ক ব্যবহার করা:
const { exec } = require('child_process');
const util = require('util');
// Convert exec to a promise-based function
const execPromise = util.promisify(exec);
async function executeCommand(command) {
try {
const { stdout, stderr } = await execPromise(command);
if (stderr) {
console.error(`Command stderr: ${stderr}`);
}
console.log(`Command output:\n${stdout}`);
return stdout;
} catch (error) {
console.error(`Error executing command: ${error.message}`);
throw error;
}
}
// Using the promise-based function
executeCommand('node --version')
.then(version => console.log(`Node.js version: ${version.trim()}`))
.catch(err => console.error('Failed to get Node.js version'));
execFile() পদ্ধতি
execFile() পদ্ধতিটি exec() এর অনুরূপ, তবে এটি একটি শেল তৈরি করে না।
এটি বহিরাগত বাইনারি চালানোর জন্য খুব দক্ষ।
const { execFile } = require('child_process');
// Execute 'node' with arguments
execFile('node', ['--version'], (error, stdout, stderr) => {
if (error) {
console.error(`Error executing file: ${error.message}`);
return;
}
console.log(`Node.js version: ${stdout.trim()}`);
});
// On Windows, execute a batch file
if (process.platform === 'win32') {
execFile('C:\\Windows\\System32\\cmd.exe', ['/c', 'echo Hello from batch!'], (error, stdout, stderr) => {
if (error) {
console.error(`Error: ${error.message}`);
return;
}
console.log(`Output: ${stdout.trim()}`);
});
}
দ্রষ্টব্য:
execFile() ব্যবহারকারীর ইনপুট সহ কমান্ড চালানোর জন্য exec() এর চেয়ে নিরাপদ কারণ এটি শেল মেটা অক্ষর প্রক্রিয়া করে না।
spawn() পদ্ধতি
spawn() পদ্ধতি প্রদত্ত কমান্ডের সাথে একটি নতুন প্রক্রিয়া শুরু করে।
exec() এর বিপরীতে, এটি আউটপুট বাফার করে না, বরং stdout এবং stderr-এ স্ট্রিম-ভিত্তিক অ্যাক্সেস প্রদান করে।
const { spawn } = require('child_process');
// Spawn a process to list files
const ls = process.platform === 'win32'
? spawn('cmd', ['/c', 'dir'])
: spawn('ls', ['-la']);
// Handle process output streams
ls.stdout.on('data', (data) => {
console.log(`stdout: ${data}`);
});
ls.stderr.on('data', (data) => {
console.error(`stderr: ${data}`);
});
ls.on('close', (code) => {
console.log(`Child process exited with code ${code}`);
});
// Spawn with options
const grep = spawn('grep', ['hello', 'input.txt'], {
cwd: '/tmp', // Working directory
env: { ...process.env, CUSTOM_ENV: 'value' },
stdio: 'pipe', // Configure stdio
detached: false, // Process group behavior
shell: false // Whether to run in a shell
});
// Handling errors
grep.on('error', (err) => {
console.error(`Failed to start subprocess: ${err.message}`);
});
কখন স্পন () ব্যবহার করবেন
spawn() বিশেষভাবে দরকারী:
stdin এর সাথে spawn() ব্যবহার করা
const { spawn } = require('child_process');
// Spawn a process that reads from stdin
const process = spawn('wc', ['-w']); // Word count
// Send data to the process's stdin
process.stdin.write('Hello world from Node.js!');
process.stdin.end(); // Signal the end of input
// Capture output
process.stdout.on('data', (data) => {
console.log(`Number of words: ${data}`);
});
fork() পদ্ধতি
Node.js প্রসেস তৈরির জন্য fork() পদ্ধতি হল spawn() এর একটি বিশেষ কেস। এটি একটি IPC চ্যানেল সেট আপ করে যা পিতামাতা এবং শিশু প্রক্রিয়াগুলির মধ্যে বার্তাগুলিকে পাস করার অনুমতি দেয়।
// In the main file (parent.js)
const { fork } = require('child_process');
// Fork a child process
const child = fork('child.js');
// Send a message to the child
child.send({ message: 'Hello from parent' });
// Receive messages from the child
child.on('message', (message) => {
console.log('Message from child:', message);
});
// Handle child process exit
child.on('close', (code) => {
console.log(`Child process exited with code ${code}`);
});
// In the child file (child.js)
console.log('Child process started', process.pid);
// Listen for messages from the parent
process.on('message', (message) => {
console.log('Message from parent:', message);
// Send a message back to the parent
process.send({ response: 'Hello from child' });
// After 3 seconds, exit the process
setTimeout(() => {
process.exit(0);
}, 8080);
});
কাঁটাচামচের সুবিধা()
ইন্টার প্রসেস কমিউনিকেশন (আইপিসি)
fork() দিয়ে তৈরি শিশু প্রক্রিয়াগুলি send() এবং মেসেজ ইভেন্ট ব্যবহার করে কনফিগার করা IPC চ্যানেলের মাধ্যমে অভিভাবক প্রক্রিয়ার সাথে যোগাযোগ করতে পারে।
জটিল ডেটা পাঠানো হচ্ছে
// In parent.js
const { fork } = require('child_process');
const child = fork('worker.js');
// Send different types of data
child.send({
command: 'compute',
data: [1, 2, 3, 4, 5],
options: {
multiply: 2,
subtract: 1
}
});
// Receive the result
child.on('message', (result) => {
console.log('Computation result:', result);
child.disconnect(); // Clean up the IPC channel
});
// In worker.js
process.on('message', (msg) => {
if (msg.command === 'compute') {
const result = msg.data.map(num => num * msg.options.multiply - msg.options.subtract);
// Send the result back to the parent
process.send({ result });
}
});
দ্রষ্টব্য:
JSON ব্যবহার করে বার্তাগুলি অব্যাহত থাকে, তাই আপনি শুধুমাত্র JSON-সম্মত ডেটা পাঠাতে পারেন (অবজেক্ট, অ্যারে, স্ট্রিং, সংখ্যা, বুলিয়ান এবং নাল)।
শিশু প্রক্রিয়া পরিচালনা
শিশু প্রক্রিয়া হত্যা
const { spawn } = require('child_process');
// Spawn a long-running process
const child = spawn('node', ['-e', `
setInterval(() => {
console.log('Still running...', Date.now());
}, 1000);
`]);
// Output from the process
child.stdout.on('data', (data) => {
console.log(`stdout: ${data}`);
});
// Kill the process after 5 seconds
setTimeout(() => {
console.log('Killing the child process...');
// Send a SIGTERM signal
child.kill('SIGTERM');
// Alternative: child.kill() - uses SIGTERM by default
}, 5000);
// Handle the exit event
child.on('exit', (code, signal) => {
console.log(`Child process exited with code ${code} and signal ${signal}`);
});
পৃথক প্রক্রিয়া
আপনি পৃথক শিশু প্রক্রিয়া তৈরি করতে পারেন যা পিতামাতার থেকে স্বাধীনভাবে চলতে থাকে:
const { spawn } = require('child_process');
const fs = require('fs');
// Create a detached process
const child = spawn('node', ['long_running_script.js'], {
detached: true,
stdio: ['ignore',
fs.openSync('output.log', 'w'),
fs.openSync('error.log', 'w')
]
});
// Unref the child to allow the parent to exit independently
child.unref();
console.log(`Started detached process with PID: ${child.pid}`);
console.log('Parent will exit while child continues running.');
// The parent can now exit, and the child will continue running
ব্যবহারিক উদাহরণ
একটি সাধারণ টাস্ক সারি তৈরি করা হচ্ছে
// In tasks.js (parent)
const { fork } = require('child_process');
const numCPUs = require('os').cpus().length;
class TaskQueue {
constructor() {
this.tasks = [];
this.workers = [];
this.maxWorkers = numCPUs;
}
addTask(task) {
this.tasks.push(task);
this.runNext();
}
runNext() {
// If we have tasks and available workers
if (this.tasks.length > 0 && this.workers.length < this.maxWorkers) {
const task = this.tasks.shift();
const worker = fork('worker.js');
console.log(`Starting worker for task ${task.id}`);
this.workers.push(worker);
worker.send(task);
worker.on('message', (result) => {
console.log(`Task ${task.id} completed with result:`, result);
// Remove this worker from our workers list
this.workers = this.workers.filter(w => w !== worker);
// Run the next task if we have one
this.runNext();
});
worker.on('error', (err) => {
console.error(`Worker for task ${task.id} had an error:`, err);
this.workers = this.workers.filter(w => w !== worker);
this.runNext();
});
worker.on('exit', (code) => {
if (code !== 0) {
console.error(`Worker for task ${task.id} exited with code ${code}`);
}
});
}
}
// Usage
const queue = new TaskQueue();
// Add some tasks
for (let i = 1; i <= 10; i++) {
queue.addTask({
id: i,
type: 'calculation',
data: Array.from({ length: 1000000 }, () => Math.random())
});
}
// In worker.js
process.on('message', (task) => {
console.log(`Worker ${process.pid} received task ${task.id}`);
// Simulate CPU-intensive work
let result;
if (task.type === 'calculation') {
// For example, find sum and average
const sum = task.data.reduce((acc, val) => acc + val, 0);
const avg = sum / task.data.length;
result = { sum, avg };
}
// Send result back to parent
process.send({ taskId: task.id, result });
// Exit this worker
process.exit(0);
});
বাহ্যিক অ্যাপ্লিকেশন চলমান
const { spawn } = require('child_process');
const path = require('path');
const fs = require('fs');
// Function to convert a video using ffmpeg
function convertVideo(inputFile, outputFile, options = {}) {
return new Promise((resolve, reject) => {
// Make sure input file exists
if (!fs.existsSync(inputFile)) {
return reject(new Error(`Input file ${inputFile} does not exist`));
}
// Prepare ffmpeg arguments
const args = ['-i', inputFile];
if (options.scale) {
args.push('-vf', `scale=${options.scale}`);
}
if (options.format) {
args.push('-f', options.format);
}
args.push(outputFile);
// Spawn ffmpeg process
const ffmpeg = spawn('ffmpeg', args);
// Collect output for logging
let stdoutData = '';
let stderrData = '';
ffmpeg.stdout.on('data', (data) => {
stdoutData += data;
});
ffmpeg.stderr.on('data', (data) => {
stderrData += data;
});
// Handle process completion
ffmpeg.on('close', (code) => {
if (code === 0) {
resolve({
inputFile,
outputFile,
stdout: stdoutData,
stderr: stderrData
});
} else {
reject(new Error(`ffmpeg exited with code ${code}\n${stderrData}`));
}
});
// Handle process errors
ffmpeg.on('error', reject);
});
}
// Example usage (commented out)
/*
convertVideo('input.mp4', 'output.webm', {
scale: '640:480',
format: 'webm'
})
.then(result => {
console.log('Video conversion successful!');
console.log(`Output file: ${result.outputFile}`)
; })
.catch(error => {
console.error('Video conversion failed:', error.message);
});
*/
সর্বোত্তম অনুশীলন
- সীমিত আউটপুট সহ সাধারণ কমান্ডের জন্য exec() ব্যবহার করুন
- দীর্ঘ-চলমান প্রক্রিয়া বা বড় আউটপুটগুলির জন্য spawn() ব্যবহার করুন
- CPU-নিবিড় Node.js অপারেশনের জন্য fork() ব্যবহার করুন
সতর্কতা:
অনেক শিশু প্রক্রিয়া চালানোর ফলে সিস্টেমের সম্পদ দ্রুত নিঃশেষ হয়ে যেতে পারে। সর্বদা হার সীমিত এবং সমসাময়িক চলমান নিয়ন্ত্রণ সক্ষম করুন।
নিরাপত্তা বিবেচনা
অনুশীলন করুন
সঠিক মডিউল নাম নির্বাচন করুন.
The ______ module provides the ability to spawn child processes in Node.js.